<?php

namespace App\Http\Controllers\api;

use App\Exceptions\AdrewardReceiveException;
use App\Models\User;
use App\Services\Wallet\AdrewardService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AdrewardController extends BaseController
{
    public function create(Request $request)
    {
        $details = $request->post('details');
        try {
            if (!is_array($details)) {
                $details = json_decode($details, true);
            }
            $result = AdrewardService::upload(auth('jwt')->user(), $details);

            return $this->success($result);
        } catch (AdrewardReceiveException $exception) {
            return $this->error($exception->getMessage(), [], 430);
        } catch (\Exception $exception) {
            Log::error($exception->getMessage());
            return $this->error("红包已被领完～");
        }
    }

    public function receive(Request $request)
    {
        try {
            /** @var User $user */
            $user = auth('jwt')->user();
            AdrewardService::receive($user);

            return $this->success('', '红包已成功领取');
        } catch (AdrewardReceiveException $exception) {
            return $this->error($exception->getMessage());
        } catch (\Exception $exception) {
            Log::error($exception->getMessage());
            return $this->error("红包已被抢空～");
        }
    }
}
